package com.ifatter.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 联网模块，该模块适应于Android1.6及以上版本，该模块支持
 * 
 * 1、CMWAP/CMNET自动切换<br />
 * 2、移动资费页面过滤<br />
 * 3、重试三次联网<br />
 * 4、Post和Get方式<br />
 * 5、支持gzip压缩
 */
public class HttpNetClient {
	
	public String asStringByPost(String url, Map<String, String> postParameters)
			throws IOException {


			String ret = "";
			HttpClient httpClient = null;
			try {
				httpClient = new DefaultHttpClient();   

				HttpPost httpPost = new HttpPost(url);
				List<NameValuePair> parameters = new ArrayList<NameValuePair>();
				if (postParameters != null) {
					Set<Map.Entry<String, String>> set = postParameters
							.entrySet();
					for (Map.Entry<String, String> entry : set) {
		
						parameters.add(new BasicNameValuePair(entry.getKey(),
								entry.getValue()));
					}
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
						parameters, HTTP.UTF_8);
				httpPost.setEntity(entity);
				HttpResponse response = httpClient.execute(httpPost);
//				if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
//					httpPost.abort();
//				}
				
				HttpEntity e = response.getEntity();
				InputStream in = e.getContent();
				if (null == in) {
					return null;
				}
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int ch;
				while ((ch = in.read()) != -1) {
					baos.write(ch);
				}
				byte[] bytes = baos.toByteArray();
				in.close();
				// 检测移动资费页 TODO

				return new String(bytes, HTTP.UTF_8);

			} catch (IOException e) {
				e.printStackTrace();
				
			} finally {
				try {
					httpClient.getConnectionManager().shutdown();
				} catch (Exception ignore) {
				}
			}
		return ret;
	}


}
